import _mysql
import pdb
import md5
import sys, traceback
try:
    import config
    reload(config)
except:
    pass
import time
import MySQLdb
from MySQLdb.cursors import *
def getLogError():
    info = sys.exc_info()
    slog = ""
    for file1, lineno, function, text in traceback.extract_tb(info[2]):
        slog += "file Name:" + str(file1) + " line " + str(lineno) + " in func:  " + str(function)
    slog += "** %s: %s" % info[:2]
    return slog
    
    
class WriteItem:
    def __init__(self, host=config.mysql_local, data=config.mysql_db, username=config.mysql_user, password=config.mysql_pass, _port=config.mysql_port):
       
        self.myarr = host
        self.data = data
        self.user = username
        self.pwd = password
        self.port = _port
        self.connect()
    def getTimeSpan(self):
        from  datetime import datetime
        ret = datetime.now() - datetime.strptime("01-01-1990", "%d-%m-%Y")
        return (ret.days * 24 * 60) + (ret.seconds / 60)
    def insert(self, table, item):
        for key in item:
            if type(item[key]) == type(u'asd'):
                item[key] = item[key].encode('utf-8')
                
        try:        
            sql = "INSERT INTO %s(" % (table)
            tmp_key = ""
            tmp_value = "VALUES("
            for key in item:        
                tmp_key = tmp_key + '`' + str(key) + '`' + ","
                if key == 'createdate' or key == 'update_time' or key == 'ctime' or key == 'mtime':
                    tmp_value = tmp_value + str(item[key]) + ","
                else:
                    tmp_value = tmp_value + '\'' + self.escaps_string(str(item[key])) + '\'' + ","
            tmp_key = tmp_key[0:len(tmp_key) - 1] + ") "
            tmp_value = tmp_value[0:len(tmp_value) - 1] + ")"
            sql = sql + tmp_key + tmp_value
            print sql
            self.excuteNonReturn(sql)
            sql = "select LAST_INSERT_ID() AS id;";
            return self.excuteReturn(sql)[0]
            return 1
        except:
            return 0
    def deletePargam(self, name, item):
        try:
            del item[name]
        except:
            pass
    def update(self, table, item, where):
        self.deletePargam('rd', item)
        self.deletePargam('function', item)        
        try:        
            sql = "UPDATE  %s " % (table)
            tmp_key = " SET "
            tmp_value = " WHERE "
            for key in item:                        
                tmp_key = tmp_key + '`' + str(key) + '`' + '=' + '\'' + self.escaps_string(str(item[key])) + '\'' + ","
            for key in where:
                print key
                tmp_value = tmp_value + '`' + str(key) + '`' + '=' + '\'' + str(where[key]) + '\'' + " AND "
            tmp_key = tmp_key[0:len(tmp_key) - 1]
            tmp_value = tmp_value[0:len(tmp_value) - 5]             
            sql = sql + tmp_key + tmp_value
            print sql
            
            self.excuteNonReturn(sql)
            return 1
        except:
            print getLogError()
            return 0
        
    def connect(self):
        while True:
            try:
                self.db = MySQLdb.connect(host=self.myarr,
                                               user=self.user,
                                               db=self.data,
                                               passwd=self.pwd ,
                                               port=self.port, charset="utf8",
                                                   cursorclass=DictCursor)
                self.db.set_character_set('utf8')
                return True
            except:
                print getLogError()
                import time
                time.sleep(2)
    def escaps_string(self, value):
        try:
            return _mysql.escape_string(value)
        except:    
            return value
    def excuteNonReturn(self, cmd):
       
        try:
            self.db.ping()
        except:
            print getLogError()
            self.connect()
        try:                        
            cursor = self.db.cursor()
            cursor.execute(cmd)
            cursor.close()
            try:
                self.db.commit()
            except:
                print getLogError();
                pass
            return 1
        except:            
            print getLogError();
            return 0
    def close(self):
        try:
            self.db.close()
        except:
            print getLogError();
    
    def excuteReturnTwoResult(self, sql):
        jdata = {}
        try:
            self.db.ping()
        except:
            self.connect()
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            jdata['res'] = cursor.fetchallDict()
            extcur = cursor.nextset()
            jdata['info'] = cursor.fetchallDict()
            cursor.close()
            try:
                self.db.commit()
            except:
                pass
        except:          
            print getLogError()
        return jdata        
    def excuteReturn(self, sql):
        jdata = []
        try:
            self.db.ping()
        except:
            self.connect()
        try:
            cursor = self.db.cursor()
            cursor.execute(sql)
            jdata = cursor.fetchallDict()
            cursor.close()
            try:
                self.db.commit()
            except:
                pass
        except:          
            print getLogError()
        return jdata
    

    
#c = WriteItem()
item = {'name':'cuongnv', 'fullname':'Nguyen Van Cuong'}
where = {'id':10, 'ct_id':11}
#c.update("item",item, where)
